package com.ruoyi.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.TlcUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.XcxUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.tlc.ITlcUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
@Qualifier("xcxUserService")
public class XcxUserServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(XcxUserServiceImpl.class);

    @Autowired
    private ITlcUserService tlcUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        LambdaQueryWrapper<TlcUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TlcUser::getOpenId,username);
        TlcUser user = null;
        try {
            user = tlcUserService.getOne(wrapper);
        }catch (Exception e){
            user = null;
        }
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("用户不存在!");
        }
        else if ("0".equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被禁用.", username);
            throw new ServiceException("用户已禁用!");
        }


        return createLoginUser(user);
    }

    public UserDetails createLoginUser(TlcUser user)
    {
        return new XcxUser(user.getId(), user.getOpenId(), user);
    }
}
